<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class JumpMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $configUrl = config('set.web_url');
        $configUrlReplaceM = str_replace(config('app.web_domain'), config('app.wap_domain'), $configUrl);
        $newUrl = explode('?', route('index'))[0];

        if (!is_mobile()) {
            if ((bool)config('set.301jump')) {
                if (strpos($newUrl, $configUrl) !== 0) {
                    return redirect($configUrl . $_SERVER['REQUEST_URI'], 301);
                }
            }
        } else {
            if ((bool)config('set.wap_jump')) {
                if (strpos($newUrl, $configUrlReplaceM) !== 0) {
                    return redirect($configUrlReplaceM . $_SERVER['REQUEST_URI'], 301);
                }
            }
        }

        return $next($request);
    }
}
